package linkedList;

import org.w3c.dom.stylesheets.LinkStyle;

import java.util.List;

public class MyLinkedList {
    class ListNode {
        public int val;
        public ListNode prev; //前驱
        public ListNode next; //后继

        public ListNode(int val) {
            this.val = val;
        }
    }

    public ListNode head;
    public ListNode last;


    public int size() {
        ListNode cur = head;
        int count = 0;
        while (cur != null) {
            cur = cur.next;
            count++;
        }
        return count;
    }

    public void display() {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    public boolean contains(int key) {
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }

    public void addFirst(int data) {
        ListNode node = new ListNode(data);
        if (head == null) {
            head = last = node;
        } else {
            node.next = head;
            head.prev = node;
            head = node;
        }
    }

    public void addLast(int data) {
        ListNode node = new ListNode(data);
        if (head == null) {
            head = last = node;
        } else {
            last.next = node;
            node.prev = last;
            last = node;
        }
    }

    public void addIndex(int index, int data) {
        ListNode cur = head;
        ListNode node = new ListNode(data);
        int count = 0;
        while (count != index - 1) {
            cur = cur.next;
            count++;
        }
        node.next = cur;
        node.prev = cur.prev;
        cur.prev.next = node;
        cur.prev = node;
    }

    public void remove(int key) {
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == key) {
                if (cur == head) {
                    //头删
                    head = head.next;
                    if (head != null) {
                        head.prev = null;
                    } else {
                        //只有一个节点
                        last = null;
                    }
                } else {
                    if (cur.next == null) {
                        //尾删
                        cur.prev.next = null;
                        last = last.prev;
                    } else {
                        cur.next.prev = cur.prev;
                        cur.prev.next = cur.next;
                    }
                }
                return;
            }
            cur = cur.next;
        }
    }

    public void removeAll(int key) {

    }

}
